﻿#include "safetycomponent.h"
#include <QTimer>

#include "componentmanager.h"
#include "grating/grating_data.h"

SafetyComponent::SafetyComponent(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	ui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
	ui.tableWidget->verticalHeader()->setVisible(false);
}

SafetyComponent::~SafetyComponent()
{
}

bool SafetyComponent::Init()
{
	m_grating = component->GetComponent(Component::component_grating);
	if (m_grating == nullptr) {
		return false;
	}
	QByteArray input;
	QByteArray output;
	m_grating->ExcuteCmd((int)GratingCmdType::get_grating_id_list, input, output);
	m_graIds = QString(output).split(';');
	if (m_graIds.size() == 0) {
		return false;
	}
	int i = 0;
	for (auto& iter : m_graIds) {
		ui.tableWidget->insertRow(i);
		auto item0 = new QTableWidgetItem(iter);
		item0->setTextAlignment(Qt::AlignCenter);
		auto item1 = new QTableWidgetItem("未知状态");
		item1->setTextAlignment(Qt::AlignCenter);
		ui.tableWidget->setItem(i, 0, item0);
		ui.tableWidget->setItem(i, 1, item1);
		i++;
	}
	UpdateTable();
	return true;
}

void SafetyComponent::UpdateTable()
{
	int i = 0;

	for (auto& iter : m_graIds) {
		QByteArray input = iter.toUtf8();
		QByteArray output;
		m_grating->ExcuteCmd((int)GratingCmdType::get_grating_trig_state, input, output);
		auto item = ui.tableWidget->item(i, 1);
		item->setText(output);
		i++;
	}

	QTimer::singleShot(1000, this, &SafetyComponent::UpdateTable);
}
